<?php


namespace app\home\service;


use app\home\model\dealer\Dealer;

class UserToken
{
    protected $model;

    static protected $instance = null;

    public function __construct(Dealer $model)
    {
        $this->model = $model;
    }


    private static function getInstance()
    {
        if (!(self::$instance instanceof self)) {
            self::$instance = new self(new Dealer());
        }
        return self::$instance;
    }

    public static function createToken()
    {
        return md5(time() . getRandChar(32) . config('salt'));
    }

    public static function verifyToken()
    {
        return self::getUserInfoByToken() ? true : false;
    }

    public static function getUserIdByToken()
    {
        return self::getUserInfoByToken()->id;
    }

    public static function getUserInfoByToken()
    {
        $token = self::getToken();
        if($token){
            $res = self::getInstance()->model->where('token', $token)->find();
            return $res;
        }
        return false;
    }

    public static function getToken()
    {
        return cookie(md5(config('salt')));
    }

}